import { Controller, Get, Inject, Post, Body, Delete, Param } from '@nestjs/common';
import { configure } from 'configure/configure.module';
import { FormValidatePipe } from '@utils/form-validate.pipe';
import { RegisterForm } from './user.forms';
import { UserService } from 'src/services/user.service';
import { NResponse } from '@type/response';
import { ErrorCode } from '@type/error-code';
import { LoginForm } from './auth.form';

@Controller(configure.appPrefix)
export class AuthController {
    constructor(private userSrv: UserService) {

    }
    @Post('/login')
    public async login(@Body(new FormValidatePipe()) form: LoginForm): NResponse.IPost<string> {
        let [err, user] = await this.userSrv.validateUser(form.username, form.password);
        if(err == 'NOT_EXIST' || err == 'PASSWORD_ERR') {
            return {code: ErrorCode.LOGIN_ERROR, msg: '账户不存在或者密码错误！', data: null}
        }
        let token = await this.userSrv.certificate(user);
        return {code: ErrorCode.SUCCESS, msg: '成功！', data: token}
    }
    public outlog() {

    }
    @Post('/register')
    public async register(@Body(new FormValidatePipe()) form: RegisterForm): NResponse.IPost<null> {
        let user: RegisterForm & {createdUserId: string, updatedUserId: string} = Object.assign(form, {createdUserId: '', updatedUserId: ''})
        let [err, _] = await this.userSrv.register(user);
        if(err) {
            if(err == 'exist') {
                return {code: ErrorCode.EXIST, msg: '账户已经存在', data: null};
            }
            return {code: ErrorCode.UNKOWN, msg: '未知错误', data: null};
            
        }
        return {code: ErrorCode.SUCCESS, msg: '成功！', data: null};
    }
}